<template>
  <div class="border">
    <label for="file-upload" style="cursor: pointer;">
      <el-icon size="25"><Picture /></el-icon>
    </label>
    <input id="file-upload" type="file" accept="image/*" style="display: none;" @change="handleImageUpload">
  </div>
  <div class="rich-text-editor">
    <!-- 富文本编辑区域 -->
    <div
        ref="editor"
        contenteditable
        class="editor"
        @paste="handlePaste"
        @keydown.enter="submit"
    ></div>
     <div class="flex-end">
       <el-button size="large" @click="submit">提交</el-button>
     </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import {fileUpload} from '@/api'

let fileInput=ref()
let editor=ref()
let emit=defineEmits(['submit'])
let insertImage=(url)=>{
  const img = document.createElement('img')
  img.src = url
  img.style.maxWidth = '100%'
  editor.value.appendChild(img)
}

let handleImageUpload=async (e)=>{
  const file = e.target.files[0]
  if (!file) return
  const result = await fileUpload('/api/file/upload/social/chat',file)
  insertImage(result.data)
  e.target.value = '' // 清除已选文件
}
/**
 * 粘贴事件
 * @param e
 */
let handlePaste=(e)=>{
  const items = e.clipboardData.items
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      const blob = items[i].getAsFile()
      const fakeEvent = { target: { files: [blob] } }
      handleImageUpload(fakeEvent)
      e.preventDefault()
    }
  }
}
let submit=()=>{
  const content = editor.value.innerHTML
  emit('submit', {
    html: content,
    text: editor.value.innerText
  })
}
</script>

<style scoped>
.rich-text-editor {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
}

.editor {
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
  outline: none;
  margin-bottom: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
}

.submit-btn {
  background: #409eff;
  color: white;
}
</style>
